﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zjs_VoteSys.Models;
using Zjs_VoteSys.Models.Database;

namespace Zjs_VoteSys.Service
{
    public class UserService:IUserService
    {
        //定义数据库上下文
        private readonly Zjs_VoteSysContext _db;
        public UserService(Zjs_VoteSysContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 判断邮箱是否存在
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool TfUserEmail(string email)
        {
            return _db.Users.Any(x => x.Email == email);
        }
        public string Reg(string email,string password)
        {
            
            //随机数1000-9999
            var salt = new Random().Next(1000, 9999);

            //123456+随机值   “E1ADC3949BA59ABBE56E057F2F883E”  //结果变化
            //222222    "E1xxxxxxxxxxxxxxxxxxxxxxxxxxxx"   //所有的组合记录下来
            //在对密码进行MD5 md5(密码+随机数)

            var md5 = MD5Helper.MD5Encrypt32(password + salt.ToString());
            var user = new User()
            {

                Email = email,
                Password = md5,
                RegisterDate=DateTime.Now,
                Salt=salt.ToString()

            };
            //上下文.表名.操作方法(需要插入的数据对象)
            _db.Users.Add(user);
            var rows = _db.SaveChanges();
            if (rows <= 0)
                return "注册失败";
            var vote = new Vote()
            {
                UserId = user.Id,
                VoteCount = 0,
                VoteDate = null,
            };
            _db.Votes.Add(vote);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return user.Email;
            }
            return "注册失败";

        }
        public User GetphoneByEmail(string Email)
        {
            return _db.Users.FirstOrDefault(x => x.Email == Email);
        }
        public string AddCom(int userId, string CompanyLogo,string Name,string Description)
        {
            var Com = new Company()
            {
                UserId = userId,
                CompanyLogo = CompanyLogo,
                Name = Name,
                Description = Description,
                CreationDate = DateTime.Now
            };
             _db.Companies.Add(Com);
            var row = _db.SaveChanges();
            if (row > 0)
            {

                return "添加成功";
            }
            return "添加失败";
        }
        public string AddAward(int userid,int companyId, int awardCategoryId,int prizeCategoryId,string projectImage)
        {
            var Com = _db.Companies.FirstOrDefault(x => x.Id == companyId);
            var awards = _db.Awards.FirstOrDefault(x => x.CompanyId == companyId && x.AwardCategoryId == awardCategoryId);

            if (Com == null)
                return "未找到该公司";
            if (awards != null)
                return "不可上传重复奖项内容";
            var award = new Award()
            {
                UserId=userid,
                CompanyId = Com.Id,
                AwardCategoryId = awardCategoryId,
                PrizeCategoryId = prizeCategoryId,
                ProjectImage = projectImage,
                PrizeDate = DateTime.Now
            };
            _db.Awards.Add(award);
            var row = _db.SaveChanges();
            if (row <= 0)
                return "添加失败";

            
            var exam = new Examine()
            {
                CompanyId = companyId,
                State = "待审核",
                AwardCategoryId=awardCategoryId
            };
            _db.Examines.Add(exam);
            var rows = _db.SaveChanges();
            if (rows <= 0)
                return "添加失败";
            return "添加成功 待审核";


        }
        public string TfAward(int userid, int awardCategoryId)
        {
            var awards = _db.Awards.FirstOrDefault(x => x.UserId ==userid  && x.AwardCategoryId == awardCategoryId);
            if (awards == null)
                return "否";
            return "是";
        }
        public string Examine(int examId,string state)
        {
            var exam = _db.Examines.FirstOrDefault(x => x.Id == examId);
            var com = _db.Companies.FirstOrDefault(x => x.Id == exam.CompanyId);
            
            if (exam == null)
                return "没有该项目";
            //先审核 再添加到项目表
            exam.State = state;
            var row = _db.SaveChanges();
            if (row <= 0)
                return "审核失败";


            if (exam.State != "通过")
                return "已拒绝该项目";

            var project = new Project()
            {
                CompanyName = com.Name,
                CompanyLogo = com.CompanyLogo,
                AwardCategoryId = exam.AwardCategoryId,
                ProjectId=exam.Id,
                VoteCount = 0
            };
            _db.Projects.Add(project);
            var rows = _db.SaveChanges();
            if (rows <= 0)
                return "审核失败";
            return "已通过该项目";
        }
        public List<ModelsProject> ModelsProject(int projectid)
        {
            var project = _db.Projects.Where(x => x.ProjectId == projectid);
            var list = project.Join(_db.AwardCategories, x => x.AwardCategoryId, y => y.Id, (x, y) => new ModelsProject
            {
                AwardName=y.AwardName,
                CompanyName=x.CompanyName,
                CompanyLogo=x.CompanyLogo,
                VoteCount=x.VoteCount
            }).ToList();
            return list;
        }
        public string Votes(int userid,int projectid)
        {
            var vote = _db.Votes.FirstOrDefault(x => x.UserId==userid);
            var project = _db.Projects.FirstOrDefault(x => x.ProjectId == projectid);
            //根据日期判断是不是第二天 自动刷新投票次数
            if (vote.VoteDate != DateTime.Now.Date)
                vote.VoteCount = 0;
            
            if (vote.VoteCount >= 5)
                return "今日票数已用完";
            vote.VoteCount++;
            vote.VoteDate = DateTime.Now.Date;
            project.VoteCount++;
            var rows = _db.SaveChanges();
            if (rows <= 0)
                return "投票失败";
            return "投票成功";
        }
        public GetProResponse getProResponse(int AwardCategoryId,string Keyword, int PageIndex, int PageSize)
        {
            //固定条件查询
            var project = _db.Projects.Where(x => x.AwardCategoryId == AwardCategoryId);
            //根据条件查询
            if (!string.IsNullOrEmpty(Keyword))
            {
                project = project.Where(x => x.CompanyName.Contains(Keyword));
            }
            //查询该条件下的总数

            var total = project.Count();
            var list = project.OrderBy(x => x.VoteCount).Skip((PageIndex - 1) * PageSize).Take(PageSize)
                .Select(x => new ProShowModel
                {
                   CompanyLogo=x.CompanyLogo,
                   CompanyName=x.CompanyName,
                   VoteCount=x.VoteCount

                })
                .ToList();
            ///构造返回对象
            var response = new GetProResponse()
            {
                List = list,
                Total = total
            };
            return response;
        }
        public GetProResponse getProjectResponse(int companyid, int PageIndex, int PageSize)
        {
            //固定条件查询
            var com = _db.Companies.Where(x => x.Id == companyid);
            var award = com.Join(_db.Awards, x => x.Id, y => y.CompanyId, (x, y) => new ProShowModels
            {
                CompanyLogo=x.CompanyLogo,
                Name=x.Name,
                Description=x.Description,
                AwardCategoryId = y.AwardCategoryId,
                PrizeCategoryId=y.PrizeCategoryId,
                PrizeDate=y.PrizeDate
            });
            //查询该条件下的总数

            var total = award.Count();
            var list = award.OrderBy(x => x.PrizeDate).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            ///构造返回对象
            var response = new GetProResponse()
            {
                List2 = list,
                Total = total
            };
            return response;
        }
    }
}
